package com.lovo.ticket.controller;

import com.lovo.config.RedisCacheUtil;
import com.lovo.dao.IMovieDao;
import com.lovo.dao.IOrderDao;
import com.lovo.dto.OrderDto;
import com.lovo.entity.MovieEntity;
import com.lovo.entity.OrderEntity;
import com.lovo.service.IRemoteService;
import com.lovo.util.PinYinUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RestController
public class TicketController {
     @Autowired
    IRemoteService remoteService;
     @Autowired
    IOrderDao orderDao;
     @Autowired
     IMovieDao movieDao;
     @Autowired
    RabbitTemplate rabbitTemplate;
     @Autowired
    RedisCacheUtil redisCacheUtil;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
     @GetMapping("movieInfo")
     public List<MovieEntity> movieInfo(){
         List<MovieEntity> list=  remoteService.movieList();
         movieDao.saveAll(list);
         return list;
     }
    @GetMapping("movieClientInfo")
    public List<MovieEntity> movieClientInfo(){

        return (List<MovieEntity>) movieDao.findAll();
    }

    /**
     * 回调方法
     */
    RabbitTemplate.ConfirmCallback callback=(CorrelationData correlationData, boolean b, String s)->{
        //投递成功
        if(b){
            String correlation=correlationData.getId();
           String strArray[]= correlation.split(",");
           //获得订单ID
               long orderId=Long.parseLong(strArray[0]);
            //获得codeId
               long codeId=Long.parseLong(strArray[1]);

             //购买电影票数量
            int movieNum=Integer.parseInt(strArray[2]);
            //修改订单状态为0
             OrderEntity orderEntity= orderDao.findById(orderId).get();
             orderEntity.setTag(0);
             orderDao.save(orderEntity);

            MovieEntity movie=  movieDao.findById(codeId).get();
        //    movie.setMovieNum(movie.getMovieNum()-order.getMovieNum());
            movie.setMovieNum(movie.getMovieNum()-movieNum);
            movieDao.save(movie);  //修改电影票的数量

        }
    };

   @PostMapping("saveOrder")
   @Transactional(rollbackFor = Exception.class)
   public boolean saveOrder(OrderEntity order,long codeId){
       //开启手动确认
       rabbitTemplate.setMandatory(true);//开启消息确认
       //绑定回调函数
       rabbitTemplate.setConfirmCallback(callback);

       //获取当前日期
       LocalDate today = LocalDate.now();
       DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
       String dateStr = today.format(fmt);
       order.setMovieDate(dateStr);
       //订单号
      String orderCode= PinYinUtil.getPinYin(order.getMovieName());
       order.setOrderCode(orderCode+codeId);
       order.setTag(3);
      order=  orderDao.save(order);  //生成订单


       //关联数据
       CorrelationData correlationData=new CorrelationData(String.valueOf(order.getOrderId())+","+codeId+","+order.getMovieNum());
      if(null!=order){

      //创建DTO用来做数据传输
          OrderDto orderDto=new OrderDto();
          //实体对象拷贝到DTO中
          BeanUtils.copyProperties(order,orderDto);
          //发送到MQ
          rabbitTemplate.convertAndSend("orderDirectExchange","order",orderDto,correlationData);
          return true;
      }else {
          return false;
      }
  }
  @GetMapping("changeOrder/{orderCode}")
  public boolean  changeOrder(@PathVariable("orderCode")String orderCode){
     OrderEntity order=    orderDao.findDistinctFirstByOrderCode(orderCode);
     order.setTag(1);
    order= orderDao.save(order);
    if(null!=order){
        return true;
    }
    return false;
  }
  @GetMapping("userOrderList/{userName}")
  public List<OrderEntity> userOrderList(@PathVariable("userName")String userName){
      return orderDao.findAllByUserName(userName);
  }
  @PostMapping("addShop")
  public boolean addShop(String key, Map<String, Object> map,long time){


       return redisCacheUtil.hmset(key,map,time);
  }


}
